package com.lu.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lu.reggie.common.R;
import com.lu.reggie.dto.DishDto;
import com.lu.reggie.dto.SetmealDto;
import com.lu.reggie.entity.Category;
import com.lu.reggie.entity.Dish;
import com.lu.reggie.entity.Setmeal;
import com.lu.reggie.entity.SetmealDish;
import com.lu.reggie.service.ICategoryService;
import com.lu.reggie.service.IDishService;
import com.lu.reggie.service.ISetmealDishService;
import com.lu.reggie.service.ISetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 前端控制器
 * </p>
 *
 * @author 况山云
 * @since 2022-08-22
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private ISetmealService iSetmealService;
    @Autowired
    private ICategoryService iCategoryService;
    @Autowired
    private ISetmealDishService iSetmealDishService;
    @Autowired
    private IDishService iDishService;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setMealCache", allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("添加的套餐信息为:{}", setmealDto.toString());
        iSetmealService.saveWithDish(setmealDto);
        return R.success("添加成功!");
    }

    /**
     * 套餐分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        //分页构造器
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        //套餐菜品分页构造器
        Page<SetmealDto> setmealDishPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //过滤
        queryWrapper.like(name != null, Setmeal::getName, name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        iSetmealService.page(setmealPage, queryWrapper);
        //copy,因为根据原有的setmeal查询没有分类字段，所以要使用dto，dto又为空，所以需要赋值，重新查询
        BeanUtils.copyProperties(setmealPage, setmealDishPage, "records");
        List<Setmeal> records = setmealPage.getRecords();
        //将每一个套餐取出，根据id查询菜品
        List<SetmealDto> setmealDtos = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Long id = item.getCategoryId();
            Category category = iCategoryService.getById(id);
            if (category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDishPage.setRecords(setmealDtos);
        return R.success(setmealDishPage);
    }


    /**
     * 删除和批量删除菜品
     * @param ids
     * @return
     */
    @CacheEvict(value = "setMealCache", allEntries = true)//清除缓存下的所有对应数据
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        iSetmealService.removeWithDish(ids);
        return R.success("删除成功!");
    }


    /**
     * 移动端展示套餐
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setMealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        //根据分类id查询套餐
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        //还有状态
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmealList = iSetmealService.list(queryWrapper);
        return R.success(setmealList);
    }


    /**
     * 移动端点击套餐图片展示套餐中所有菜品信息
     * @param setmealId
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> dishList(@PathVariable("id") Long setmealId) {
        //现根据套餐id查询出所有菜品
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealId);
        List<SetmealDish> setmealDishList = iSetmealDishService.list(queryWrapper);
        //前端需要展示的是菜品的信息，所以还需要去查找菜品信息
        //但是需要的分数这个属性dish表无，在套餐菜品表中，所以需要使用到dto
        List<DishDto> dishDtoList = setmealDishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将每个copies赋值给dto
            dishDto.setCopies(item.getCopies());
            //BeanUtils.copyProperties(item, dishDto);
            String dishId = item.getDishId();
            Dish dish = iDishService.getById(dishId);
            BeanUtils.copyProperties(dish, dishDto);

            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }


    /**
     * 通用修改套餐状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        //根据id去setmeal查询套餐信息
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, Setmeal::getId, ids);
        List<Setmeal> setmealList = iSetmealService.list(queryWrapper);
        for (Setmeal setmeal : setmealList) {
            if (setmeal != null) {
                setmeal.setStatus(status);
                iSetmealService.updateById(setmeal);
            }
        }
        return R.success("状态修改成功!");
    }


    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id) {
        SetmealDto setmealDto = iSetmealService.getSetmeal(id);
        return R.success(setmealDto);
    }


    @PutMapping
    public R<String> add(@RequestBody SetmealDto setmealDto) {
        //setmealdish表数据更新应该先删除后添加
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        Long setmealDtoId = setmealDto.getId();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealDtoId);
        iSetmealDishService.remove(queryWrapper);

        //再添加
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(Long.toString(setmealDtoId));
        }
        //保存
        iSetmealDishService.saveBatch(setmealDishes);
        iSetmealService.updateById(setmealDto);
        return R.success("修改成功!");
    }


}
